package work.atpgroup.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import work.atpgroup.entity.ResourceLink;
import work.atpgroup.entity.tool.ApplicationProperties;
import work.atpgroup.service.PermissionService;
import work.atpgroup.service.ResourceService;

import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

/**
 * 资源获取类
 * **/
@Controller
public class ResourceBedController {
    @Resource(name="resourceService")
    private ResourceService resourceService;
    @Resource(name="permissionService")
    private PermissionService permissionService;
    /**
     * 私有资源，可使用id来处理和编制
     * **/
    @GetMapping("/resources/{resourceId}")
    public void getResource(@PathVariable String resourceId, HttpServletResponse response){
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        System.out.println("try parse: \n\n\n"+resourceId);
        try{
            int resource_id = Integer.parseInt(resourceId);
            System.out.println("request: parsed"+resource_id);
            String relative_path = resourceService.getResourceLinkPathById(resource_id);
            File file = new File(resourceService.getPrivateResourceAbsolutePath(relative_path));
            System.out.println("file =" +file);
            tackle_stream(file,relative_path,in,out,response);
        }catch ( NumberFormatException ignored){
        }
    }
    /**
     * 和上面的处理效果是差不多效果，就是处理方式不太一样
     * **/
    @RequestMapping("/resource/{resourceId}")
    public ResponseEntity<byte[]> download(@PathVariable String resourceId, @RequestHeader("User-Agent") String userAgent, HttpServletRequest request,HttpServletResponse response) throws IOException {
        int resource_id = Integer.parseInt(resourceId);
        String relative_path = resourceService.getResourceLinkPathById(resource_id);
        File file = new File(resourceService.getPrivateResourceAbsolutePath(relative_path));
        HttpHeaders headers = new HttpHeaders();
        if(file.getPath().endsWith(".css")){
            response.setContentType("text/css");
        }else if(file.getPath().endsWith(".js")){
            response.setContentType("text/javascript");
        }else{
            response.setContentType(new MimetypesFileTypeMap().getContentType(file)); // 设置response内容的类型
        }
        if(userAgent.indexOf("MISE")>0||userAgent.indexOf("Trident")>0||userAgent.indexOf("Edge")>0){
            try{
                headers.setContentDispositionFormData("attachment", URLEncoder.encode(relative_path,"UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }else{
            headers.setContentDispositionFormData("attachment",new String(relative_path.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        }
        return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
    }
    /**
     * 公有资源，使用公有地址来访问
     * **/
    @GetMapping("/resource_bed/**/{resource_path}")
    public void getPublicResource(String resource_path, HttpServletRequest request, HttpServletResponse response){
        resource_path = request.getServletPath().substring("/resource_bed/".length());
        getLocalResource(resource_path, response);
    }

    private void getLocalResource(String resourcepath, HttpServletResponse response) {
        if(resourcepath.startsWith(".")){
            return;// 初始目的是初级过滤无效路径和避免 ../此类的注入路径（对于第二点似乎不必要）
        }
        ResourceLink resourceLink = resourceService.getResourceLinkByPath(resourcepath);
        if((!resourceLink.getStatus())&&permissionService.getPermissionById(ApplicationProperties.permissionId).getResourcePermission()){
            return;// 资源需要权限，而本资源没有被公开(赋予权限)
        }
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        File file = new File(resourceService.getPrivateResourceAbsolutePath(resourcepath));
        tackle_stream(file,resourcepath,in,out,response);
    }
    public void tackle_stream(File file,String relative_path,BufferedInputStream in,BufferedOutputStream out,HttpServletResponse response){
        try {
            in = new BufferedInputStream(Files.newInputStream(file.toPath()));
            out = new BufferedOutputStream(response.getOutputStream());
            System.out.println("request in tackle_stream:\n\n\n     "+file.getPath());
            if(file.getPath().endsWith(".css")){
                response.setContentType("text/css");
            }else if(file.getPath().endsWith(".js")){
                response.setContentType("text/javascript");
            }else{
                response.setContentType(new MimetypesFileTypeMap().getContentType(file)); // 设置response内容的类型
            }
            response.setHeader("Content-disposition", "attachment;filename=" + relative_path);// 设置头部信息
            byte[] buffer = new byte[10240];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            out.flush();
        } catch (IOException ignored) {
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
